﻿// © 2009 Michele Leroux Bustamante. All rights reserved. 
// See http://wcfguidanceforwpf.codeplex.com for related whitepaper and updates
// For an intro to WCF see Michele's book: Learning WCF, O'Reilly 2007 (updated August 2008 for VS 2008)
// See http://www.thatindigogirl.com for the book code!

using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using Entities;
using System.ServiceModel.Web;
using System.ServiceModel;
using System.Diagnostics;
using System.ServiceModel.Description;
using Contracts;
using System.Collections.Generic;
using WPFInterview;
using System.Threading;

namespace TodoList.WpfClient
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class WCFclient : UserControl
    {
        
        private ObservableCollection<TodoItem> _ToDoItems = new ObservableCollection<TodoItem>();
        private WebChannelFactory<ITodoListService> _ChannelFactory;
        private ITodoListService _Proxy;


        public class DialogsTest : IQuestion
        {
            public string TestName
            {
                get { return "WCF - REST"; }
            }

            public UserControl getUserControl()
            {
                return new WCFclient();
            }
        }
        /// <summary>
        /// Will hold the newly created Item (top of the screen)
        /// </summary>
        private TodoItem _NewTodo;

        private void WorkerThread()
        {
            using (WebServiceHost host = new WebServiceHost(typeof(TodoList.TodoListService)))
            {
                host.Open();
            }
            while (true)
            {
                // Wake up every 5 seconds.
                Thread.Sleep(5000);
            }
        }

        public WCFclient()
        {
            InitializeComponent();

            // Prepare the task creation panel
            PriorityComboBox.ItemsSource = TodoItem.PriorityFlags;
            _NewTodo = new TodoItem {Priority = PriorityFlag.Normal, DueDate = DateTime.Today};
            NewItemPanel.DataContext = _NewTodo;

            ThreadStart threadStart = new ThreadStart(WorkerThread);
            Thread thread = new Thread(threadStart);
            thread.Start();

            //Making sure we do not call the web service at design time
            if (!DesignerProperties.GetIsInDesignMode(new DependencyObject()))
            {
                
                _ChannelFactory = new WebChannelFactory<ITodoListService>("default");
                _Proxy = _ChannelFactory.CreateChannel();
                _ToDoItems  = new ObservableCollection<TodoItem>(_Proxy.GetItems());

                foreach (TodoItem item in _ToDoItems)
                {
                    item.PropertyChanged += Item_PropertyChanged;
                }
                TodoDataGrid.ItemsSource = _ToDoItems;
                
            }

        }
        /// <summary>
        ///  A TodoItem was modified... 
        ///     Let's relay the changes to the web service
        /// </summary>
        void Item_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            // an Item has changed let's update the web service
            TodoItem item = (TodoItem) sender;
            _Proxy.UpdateItem(item.ID, item);
        }

        /// <summary>
        ///  Add a TodoItem
        /// </summary>
        private void AddTodoButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            try
            {
                _NewTodo.CreationDate = DateTime.Today;
                _NewTodo.Description = DescriptionTextBox.Text;
                _NewTodo.DueDate = DueDatePicker.SelectedDate.GetValueOrDefault(DateTime.Today);
                _NewTodo.Title = TitleTextBox.Text;
                _NewTodo.Priority = (PriorityFlag) PriorityComboBox.SelectedItem;

                _NewTodo.ID = _Proxy.CreateItem(_NewTodo);

                _NewTodo.PropertyChanged += Item_PropertyChanged;
                _ToDoItems.Add(_NewTodo);
                _NewTodo = new TodoItem { Priority = PriorityFlag.Normal, DueDate = DateTime.Today };
                NewItemPanel.DataContext = _NewTodo;
                TitleTextBox.Focus(); 

            }
            catch (Exception ex)
            {
                DescriptionTextBox.Text = _NewTodo.Description;
                TitleTextBox.Text = _NewTodo.Title;
                MessageBox.Show(ex.Message);
            }

        }


        private void DeleteTodoItem_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            // Remove todoItem from the list
            if(MessageBox.Show("Ok to delete this Item?","Deleting Todo",MessageBoxButton.OKCancel,MessageBoxImage.Exclamation)==MessageBoxResult.OK)
            {
                TodoItem item = (TodoItem)((Button) sender).DataContext;
                _Proxy.DeleteItem(item.ID);
                item.PropertyChanged -= Item_PropertyChanged;
                _ToDoItems.Remove(item);
            }
        }

    }
}
